package com.dragons.dragonsvf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragons.dragonsvf.config.DynamicMinioConfig;
import com.dragons.dragonsvf.controller.minio.ImageInfo;
import com.dragons.dragonsvf.entities.Product;
import com.dragons.dragonsvf.entities.ProductDTO;
import com.dragons.dragonsvf.entities.ResponseDTO;
import com.dragons.dragonsvf.utils.image_compress.ImageCompressionUtil;
import io.minio.Result;
import io.minio.messages.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Dragons.G
 * @date 2025-07-24 17:42:06
 * @description 图片管理控制器
 */
@RestController
public class ImageCtrl {

    private static final Logger log = LoggerFactory.getLogger(ImageCtrl.class);

    @Autowired
    DynamicMinioConfig minioConfig;

    @RequestMapping("/getImageList") // 获取桶中的图片信息
    public ResponseDTO getImageList(@RequestBody ImageInfo imageInfo){

        List<ImageInfo> products = null;
        try {
            products = minioConfig.listObjectNames(imageInfo.getBucketName());
            log.info("查询"+imageInfo.getBucketName()+"桶文件信息成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseDTO res = new ResponseDTO();
        res.setCode(200);
        res.setData(getPageData(products,imageInfo.getCurrentPage(), imageInfo.getPageSize()));
        res.setMsg("查询图片信息成功");
        return res;
    }

    @RequestMapping("/getImageListCount") // 获取桶中的图片信息
    public ResponseDTO getImageListCount(@RequestBody ImageInfo imageInfo){

        List<ImageInfo> products = null;
        try {
            products = minioConfig.listObjectNames(imageInfo.getBucketName());
            log.info("查询"+imageInfo.getBucketName()+"桶文件数量成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseDTO res = new ResponseDTO();
        res.setCode(200);
        res.setData(products.size());
        res.setMsg("查询图片信息成功");
        return res;
    }

    @PostMapping(value = "/uploadImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseDTO uploadImage(
        @RequestParam("avatar") MultipartFile file, // 和前端fieldName一致
        @RequestParam(required = false) Map<String, String> formData
    ) throws Exception {
        MultipartFile multipartFile = ImageCompressionUtil.compressMultipartFile(file);
        String s = minioConfig.putBannerProductObject(multipartFile);
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setCode(200);
        responseDTO.setMsg("文件上传成功");
        responseDTO.setData(s);
        return responseDTO;
    }

    @RequestMapping("/deleteImage") // 获取桶中的图片信息
    public ResponseDTO deleteImage(@RequestBody ImageInfo imageInfo){

        boolean products = false;
        try {
            products = minioConfig.removeObject(imageInfo.getBucketName(), imageInfo.getFileName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseDTO res = new ResponseDTO();
        res.setCode(200);
        res.setData(products);
        res.setMsg("图片删除成功");
        return res;
    }

    /**
     * 获取ImageInfo列表的分页数据
     * @param data 原始ImageInfo列表
     * @param currentPage 当前页码（从1开始）
     * @param pageSize 每页显示的记录数
     * @return 当前页的ImageInfo列表，如果没有数据则返回空列表
     */
    public static List<ImageInfo> getPageData(List<ImageInfo> data, int currentPage, int pageSize) {
        // 创建返回结果列表
        List<ImageInfo> result = new ArrayList<>();

        // 验证参数合法性
        if (data == null || data.isEmpty()) {
            return result;
        }
        if (currentPage < 1) {
            currentPage = 1;
        }
        if (pageSize < 1) {
            pageSize = 10; // 默认每页10条
        }

        // 计算起始索引和结束索引
        int startIndex = (currentPage - 1) * pageSize;
        // 如果起始索引超过数据总数，返回空列表
        if (startIndex >= data.size()) {
            return result;
        }

        // 计算结束索引，取最小值防止越界
        int endIndex = Math.min(startIndex + pageSize, data.size());

        // 截取数据并添加到结果列表
        for (int i = startIndex; i < endIndex; i++) {
            result.add(data.get(i));
        }

        return result;
    }

}
